﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;
using DG.Tweening;

public class ItemPanelDrag : MonoBehaviour, IBeginDragHandler,IDragHandler,IEndDragHandler
{
    private bool isInPhoto = false;
    public void OnBeginDrag(PointerEventData eventData)
    {
        MakePhoto.Instance.ItemPanelposMove(false);
        MakePhoto.Instance.LeftParent(this.gameObject);
    }

    public void OnDrag(PointerEventData eventData)
    {

        SetDraggedPosition(eventData);
        
    }




    // Use this for initialization
    void Start () {
    
		
	}

    // Update is called once per frame

    public virtual void SetDraggedPosition(PointerEventData eventData)
    {
        var rt = gameObject.GetComponent<RectTransform>();

        // transform the screen point to world point int rectangle
        Vector3 globalMousePos;
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, eventData.position, eventData.pressEventCamera, out globalMousePos))
        {
            rt.position = globalMousePos;
        }
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        MakePhoto.Instance.ItemPanelposMove(true);
        if (isInPhoto) {
            return;
        }
        
        if (this.transform.localPosition.x >= -500 && this.transform.localPosition.x <= 500 && this.transform.localPosition.y >= -260 && this.transform.localPosition.y <= 260&&MakePhoto.Instance.PhotoCount<=9)
        {
            GameObject clone = GameObject.Instantiate(this.gameObject);
           clone.name= clone.name.Replace("(Clone)", string.Empty);
            MakePhoto.Instance.SetItemPanelParent(clone);
            isInPhoto = true;
            MakePhoto.Instance.AddPhotoCount();
            MakePhoto.Instance.AddList(this.gameObject);

        }
        else
        {
           
            MakePhoto.Instance.SetItemPanelParent(this.gameObject);
        }
    }

    private void Update()
    {
       if(!isInPhoto) {
            return;
       }
       
        if (this.transform.localPosition.x < -500)
        {
            Vector3 vect = this.transform.localPosition;
            vect.x = -499;
            transform.localPosition = vect;
        }
        if (this.transform.localPosition.x >500)
        {
            Vector3 vect = this.transform.localPosition;
            vect.x = 499;
            transform.localPosition = vect;
        }
        if (this.transform.localPosition.y < -260)
        {
            Vector3 vect = this.transform.localPosition;
            vect.y = -259;
            transform.localPosition = vect;
        }
        if (this.transform.localPosition.y > 260)
        {
            Vector3 vect = this.transform.localPosition;
            vect.y = 259;
            transform.localPosition = vect;
        }
    }
}
